<!-- 
 上传图片添加水印组件 
 -->
<template>
	<view class="main">
		<view class="list" v-for="(item, index) in list" :key="index">
			<view class="box">
				<image @click="preImg(item)" class="img" :src="item" mode="aspectFill"></image>
				<view class="del" @click="delImage(item)">
					<u-icon name="close" color="#ffffff" size="12"></u-icon>
				</view>
			</view>
		</view>
		<view class="box" v-if="showAdd" @click="addImages">
			<u-icon name="plus" color="#ceccca" size="28"></u-icon>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				list: [], // 上传图片列表
				limit: 9, // 最大上传图片数量
				showAdd: true, // 是否显示上传图片按钮
				nowlength: 0, // 当前选择的图片数量
				nowupload: 0, //当前上传的图片数量
			}
		},
		created() {

		},
		watch: {
			list: {
				handler(nval) {
					if (nval.length >= this.limit) {
						this.showAdd = false
					} else {
						this.showAdd = true
					}
				},
			}
		},
		methods: {
			// 上传图片
			addImages() {
				uni.chooseMedia({
					count: this.limit,
					mediaType: ['image'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 当前选择的图片数量
						this.nowlength = res.tempFiles.length;
						res.tempFiles.forEach((item) => {
							if (this.list.length >= this.limit) {
								this.showAdd = false
							} else {
								uni.showLoading({
									title: '上传中',
									mask: true
								});
								// 获取图片信息
								this.getImgInfo(item.tempFilePath)
							}
						})
					}
				})
			},
			// 获取图片信息
			getImgInfo(imgUrl) {
				uni.getImageInfo({
					src: imgUrl,
					success: (res) => {
						// 创建画板
						this.createCanvas(res.width, res.height, imgUrl)
					}
				})
			},
			// 创建画板
			async createCanvas(w, h, img) {
				// 创建离屏 2D canvas 实例
				const canvas = wx.createOffscreenCanvas({
					type: '2d',
					width: w,
					height: h,
					compInst: this
				});
				// 获取 context。注意这里必须要与创建时的 type 一致
				const context = canvas.getContext('2d');

				// 创建一个图片
				const image = canvas.createImage();
				// 等待图片加载
				await new Promise(resolve => {
					image.onload = resolve
					image.src = img // 要加载的图片 url
				});

				// 把图片画到离屏 canvas 上
				context.clearRect(0, 0, w, h);
				context.drawImage(image, 0, 0, w, h);

				// 增加水印
				context.translate(w / 2, h / 2);
				context.rotate(-30 * Math.PI / 180);

				// 文字大小，位置和数量
				let horizontal = w / 6;
				let vertical = h / 3;
				let fonsize = w / 30;
				for (let i = 0; i <= 8; i++) {
					for (let j = 0; j <= 6; j++) {
						context.beginPath();
						context.font = `${fonsize}px serif`;
						context.fillStyle = '#000000';
						context.fillText('不重要的水印', (i * horizontal - w / 2) * 2, j * vertical - h, fonsize * 30);
					}
				};

				// 获取画完后的数据
				uni.canvasToTempFilePath({
					canvas: canvas,
					success: (res) => {
						// 上传图片到服务器操作
						this.upload(res.tempFilePath);
					}
				}, this);
			},

			// 图片预览
			preImg(item) {
				uni.previewImage({
					urls: this.list,
					count: item
				})
			},

			// 删除图片
			delImage(item) {
				let index = this.list.findIndex((items) => {
					return items == item
				});
				if (index != -1) {
					this.list.splice(index, 1)
				}
			},

			// 上传图片到服务器
			upload(url) {
				// uni.uploadFile({
				// 	url: '', //api地址
				// 	filePath: url, // 临时文件url
				// 	name: 'file', // 文件对应的 key
				// 	formData: {
				// 		'user': 'test'
				// 	}, //HTTP 请求中其他额外的 form data
				// 	success: (res) => {
				this.nowupload++;
				this.list.push(url);
				if (this.nowlength == this.nowupload) {
					uni.hideLoading()
				}
				// 	}
				// })
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		width: 100%;
		height: 100%;
		display: flex;
		flex-wrap: wrap;

		padding: 24rpx;
		box-sizing: border-box;

		.list {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
		}

		.box {
			width: 150rpx;
			height: 150rpx;
			border-radius: 10rpx;
			border: 1rpx solid #e7e6e4;
			margin: 4rpx;
			display: flex;
			overflow: hidden;
			align-items: center;
			justify-content: center;
			position: relative;

			.del {
				width: 28rpx;
				height: 28rpx;
				border-radius: 0 0 0 10rpx;
				background-color: #ff0000;
				position: absolute;
				top: 0;
				right: 0;
				z-index: 2;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.img {
				width: 100%;
				height: 100%;
				display: block;
			}
		}
	}
</style>
